﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using HtmlAgilityPack;
using SC2TV.Object;
using SC2TV.Tools;

namespace SC2TV.ViewModel
{
    public class ClientViewModel : BaseViewModel
    {
        public ClientViewModel()
        {
            if (DesignerProperties.IsInDesignTool)
                return;

            Favorites = new ObservableCollection<StreamTile>();
            FanStreams = new ObservableCollection<StreamTile>();
            RealStreams = new ObservableCollection<StreamTile>();
            GOSU = new ObservableCollection<StreamTile>();
            PrivateMessages = new ObservableCollection<PrivateMessageIn>();
        }

        public ObservableCollection<StreamTile> Favorites { get; set; }
        public ObservableCollection<StreamTile> FanStreams { get; set; }
        public ObservableCollection<StreamTile> RealStreams { get; set; }
        public ObservableCollection<StreamTile> GOSU { get; set; }

        public ObservableCollection<PrivateMessageIn> PrivateMessages { get; set; }

        private bool busy;

        public async Task Load()
        {
            if (busy)
                return;
            busy = true;
            try
            {
                Favorites = new ObservableCollection<StreamTile>();
                FanStreams = new ObservableCollection<StreamTile>();
                RealStreams = new ObservableCollection<StreamTile>();
                GOSU = new ObservableCollection<StreamTile>();
                PrivateMessages = new ObservableCollection<PrivateMessageIn>();

                var requester = new Requester("http://sc2tv.ru");
                var response = await requester.Get();
                var html = new HtmlDocument();
                html.LoadHtml(response.Html);

                var fanStreamsHtml = html.DocumentNode.SelectNodes("//*[@id=\"block-sc2tv_player-2\"]/div/div[2]/ul/li");
                if (fanStreamsHtml != null)
                {
                    foreach (var stream in fanStreamsHtml)
                    {
                        string imageSource = stream.SelectSingleNode("div/div/img").GetAttributeValue("src", "");
                        var temp = new StreamTile
                        {
                            Title = stream.SelectSingleNode("div/div[2]/strong").InnerText,
                            Picture =
                                new BitmapImage(imageSource == "/sites/all/themes/sc2tv/images/thumb-error.jpg"
                                    ? new Uri("/Assets/logo.png", UriKind.Relative)
                                    : new Uri(imageSource)),
                            Rating = stream.SelectSingleNode("div/div[2]/p").InnerText,
                            Description = stream.SelectSingleNode("div/div[2]/p[2]").InnerText,
                            ChannelUri = stream.SelectSingleNode("a").GetAttributeValue("href", "")
                        };
                        FanStreams.Add(temp);
                    }
                }

                var GOSUStreamsHtml = html.DocumentNode.SelectNodes("//*[@id=\"block-sc2tv_player-5\"]/div/div[2]/ul/li");
                if (GOSUStreamsHtml != null)
                {
                    foreach (var stream in GOSUStreamsHtml)
                    {
                        string imageSource = stream.SelectSingleNode("div/div/img").GetAttributeValue("src", "");
                        var temp = new StreamTile
                        {
                            Title = stream.SelectSingleNode("div/div[2]/strong").InnerText,
                            Picture =
                                new BitmapImage(imageSource == "/sites/all/themes/sc2tv/images/thumb-error.jpg"
                                    ? new Uri("/Assets/logo.png", UriKind.Relative)
                                    : new Uri(imageSource)),
                            Rating = stream.SelectSingleNode("div/div[2]/p").InnerText,
                            Description = stream.SelectSingleNode("div/div[2]/p[2]").InnerText,
                            ChannelUri = stream.SelectSingleNode("a").GetAttributeValue("href", "")
                        };
                        GOSU.Add(temp);
                    }
                }

                var REALStreamsHtml = html.DocumentNode.SelectNodes("//*[@id=\"block-sc2tv_player-6\"]/div/div[2]/ul/li");
                if (REALStreamsHtml != null)
                {
                    foreach (var stream in REALStreamsHtml)
                    {
                        if (
                            stream.SelectSingleNode("a")
                                .GetAttributeValue("href", "")
                                .Equals("/content/stream-requirements"))
                            continue;

                        string imageSource = stream.SelectSingleNode("div/div/img").GetAttributeValue("src", "");
                        var temp = new StreamTile
                        {
                            Title = stream.SelectSingleNode("div/div[2]/strong").InnerText,
                            Picture =
                                new BitmapImage(imageSource == "/sites/all/themes/sc2tv/images/thumb-error.jpg"
                                    ? new Uri("/Assets/logo.png", UriKind.Relative)
                                    : new Uri(imageSource)),
                            Rating = stream.SelectSingleNode("div/div[2]/p").InnerText,
                            Description = stream.SelectSingleNode("div/div[2]/p[2]").InnerText,
                            ChannelUri = stream.SelectSingleNode("a").GetAttributeValue("href", "")
                        };
                        RealStreams.Add(temp);
                    }
                }

                var FavoriteStreamsHtml =
                    html.DocumentNode.SelectNodes("//*[@id=\"block-sc2tv_favorites-0\"]/div/div[2]/ul/li");
                if (FavoriteStreamsHtml != null)
                {
                    foreach (var stream in FavoriteStreamsHtml)
                    {
                        string imageSource = stream.SelectSingleNode("div/div/img").GetAttributeValue("src", "");
                        var temp = new StreamTile
                        {
                            Title = stream.SelectSingleNode("div/div[2]/strong").InnerText,
                            Picture = new BitmapImage(new Uri("/Assets/logo.png", UriKind.Relative)),
                            //new BitmapImage(imageSource == "/sites/all/themes/sc2tv/images/thumb-error.jpg"
                            //    ? new Uri("/Assets/logo.png", UriKind.Relative)
                            //    : new Uri(imageSource)),
                            Rating = stream.SelectSingleNode("div/div[2]/p").InnerText,
                            Description = stream.SelectSingleNode("div/div[2]/p[2]").InnerText,
                            ChannelUri = stream.SelectSingleNode("a").GetAttributeValue("href", "")
                        };
                        Favorites.Add(temp);
                    }
                }

                if (response.StatusCode != HttpStatusCode.OK)
                    MessageBox.Show(response.StatusCode.ToString());

                requester = new Requester("http://sc2tv.ru/messages");
                response = await requester.Get();
                html.LoadHtml(response.Html);
                var messages =
                    html.DocumentNode.SelectNodes("//table [@class=\"privatemsg-list sticky-enabled\"]/tbody/tr");

                foreach (var message in messages)
                {
                    var participants = "";
                    var participantsNodes = message.SelectNodes("td[3]/a");
                    if (participantsNodes != null)
                        participants = participantsNodes.Aggregate(participants,
                            (current, participant) => current + (participant.InnerText + ", "));

                    PrivateMessages.Add(new PrivateMessageIn
                    {
                        Title = message.SelectSingleNode("td[2]/a").InnerText,
                        MessageUrl = message.SelectSingleNode("td[2]/a").GetAttributeValue("href", ""),
                        Participants = participants,
                        Date = message.SelectSingleNode("td[4]").InnerText
                    });
                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                busy = false;
            }
        }

        public ICommand Refresh
        {
            get { return new ActionCommand(async () => await Load()); }
        }

    }
}
